package io.gitee.zicai.bus.adaptor;

import io.gitee.zicai.bus.bus.Bus;
import io.gitee.zicai.bus.bus.IReceiveBus;
import io.gitee.zicai.bus.core.IBusReceiver;
import io.gitee.zicai.bus.exception.BusAdaptorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.annotation.Resource;
import java.util.Map;

/**
 * BaseBusReceiveAdaptor
 *
 * @author zicai
 * @since 2021-01-19
 */
@Slf4j
public abstract class BaseBusReceiveAdaptor<R extends IBusReceiver, RB extends IReceiveBus<R, RT>, RT> implements IBusReceiveAdaptor<R, RB, RT> {

    @Resource
    protected ApplicationContext applicationContext;
    @Resource
    protected Bus bus;

    /**
     * 厂商的指令接收服务
     *
     * @param brandName 厂商名称
     * @return IBusReceiver
     */
    @Override
    public R getCmdReceiver(String brandName) {
        Map<String, IBusReceiver> receiverMap = applicationContext.getBeansOfType(IBusReceiver.class);
        log.info(">>> IBusReceiver beanName -> {}", String.join(",", receiverMap.keySet()));
        //noinspection unchecked
        return receiverMap.entrySet().stream()
                .filter(entry -> entry.getKey().contains(brandName))
                .findFirst()
                .map(Map.Entry::getValue)
                .map(r -> (R) r)
                .orElseThrow(BusAdaptorException.ofSupplier("未找到厂商的指令接收服务"));
    }
}
